package com.xjtu.platform.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xjtu.platform.common.page.QueryAction;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;


import com.sun.mail.util.MailSSLSocketFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Utils {



    public static <T> Map<String,Object> getPage(PageParam pageParam , QueryAction<T> queryAction){
        //执行映射器方法之前立即执行分页参数（页码和每页记录数）的设置
        PageHelper.startPage(pageParam);

        List<T> list = queryAction.execute();

        //执行映射器方法之后，立即执行PageInfo对象的创建
        PageInfo<T> pageInfo = new PageInfo<T>(list);

        Map<String,Object> page = new HashMap<>();
        page.put("current", pageInfo.getPageNum());//当前页
        page.put("pageSize",pageInfo.getPageSize());//每页最大记录数
        page.put("total",pageInfo.getTotal());//总记录数
        page.put("pages",pageInfo.getPages());//总页数
        page.put("size",pageInfo.getSize());//当前页实际记录数
        page.put("list",pageInfo.getList());//当前页的数据记录
        page.put("first",1);
        page.put("pre",pageInfo.getPrePage());
        page.put("next",pageInfo.getNextPage());
        page.put("last",pageInfo.getPages());

        return page;

    }




    /**
     * 将一个Java对象转换为json串，并向浏览器（客户端）输出
     * @param resp 响应对象
     * @param obj 需要转化为json串的java对象
     * @throws IOException
     */

    public static void outJson(HttpServletResponse resp, Object obj) throws IOException {
        //json格式的媒体标准：application/json
        resp.setContentType("application/json;charset=UTF-8");//设置字符编码
        PrintWriter out = resp.getWriter();//获取向客户端发送字符信息流对象
        // 将list集合对象转化为json格式字符串
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(obj);
        out.print(jsonString);

        out.flush();
        out.close();
    }

    public static void sendMail(String targetmail, String content) throws Exception {

        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");  //设置邮件服务器
        prop.setProperty("mail.transport.protocol", "smtp"); // 邮件发送协议SMTP
        prop.setProperty("mail.smtp.auth", "true"); // 验证用户名密码

        // 邮箱设置SSL加密
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);


        //创建定义整个应用程序所需的环境信息的 Session 对象

        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                //发件人邮件用户名、授权码
                return new PasswordAuthentication("2014894101@qq.com", "rtyhrwledlliehgb");
            }
        });


        //开启Session的debug模式，可以查看到程序发送Email的运行过程
        session.setDebug(true);

        //通过session得到transport对象
        Transport ts = session.getTransport();

        //使用邮箱的用户名和授权码连上邮件服务器，这里使用已完成POP3\SMTP授权的我的账号
        ts.connect("smtp.qq.com", "2014894101@qq.com", "rtyhrwledlliehgb");

        //创建邮件对象
        MimeMessage message = new MimeMessage(session);

        //指明邮件的发件人
        message.setFrom(new InternetAddress("2014894101@qq.com"));

        //指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(targetmail));

        //邮件的标题
        message.setSubject("易心理");

        //邮件的文本内容,目前尚未尝试html格式
        message.setContent(content, "text/html;charset=UTF-8");

        //发送邮件
        ts.sendMessage(message, message.getAllRecipients());

        ts.close();
    }

    public static String produceCode(){
        return String.valueOf(new Random().nextInt(900000)+100000);
    }

    public static void xlsFileExecutor(List<? extends Object> data, String[] header, String filename) {
        System.out.println("正在生成 "+filename+" 的结案报告！");
        String[] fieldNames = fieldName(data.get(0).getClass());
        Workbook workbook = new HSSFWorkbook();
        int rowSize = 0;
        Sheet sheet = workbook.createSheet();
        Row row = sheet.createRow(rowSize);
        for (int i = 0; i < header.length; i++) {
            row.createCell(i).setCellValue(header[i]);
        }
        try {
            for (int x = 0; x < data.size(); x++) {
                rowSize = 1;
                Row rowNew = sheet.createRow(rowSize + x);
                for (int i = 0; i < header.length; i++) {
                    Object object = data.get(x);
                    for (int i1 = 0; i1 < fieldNames.length; i1++) {
                        String methodName = "get" + fieldNames[i].substring(0,             1).toUpperCase() + fieldNames[i].substring(1);//获取属性的get方法名
                        Method method1 = object.getClass().getMethod(methodName);
                        Object invoke = method1.invoke(object);//获取属性值
                        rowNew.createCell(i).setCellValue(invoke.toString());
                    }
                }
            }
        } catch (Exception e) {

        }
        OutputStream outputStream = null;
        try {
            String pathhh=Constants.FILE_DIR+filename+".xls";
            outputStream = new FileOutputStream(pathhh);
            System.out.println("工具生成的文件在*"+pathhh);
            workbook.write(outputStream);
        } catch (Exception e) {

        } finally {
            try {
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (Exception e) {

            }
            try{
                if(workbook != null){
                    workbook.close();
                }
            } catch (Exception e){

            }
        }

    }

    private static String[] fieldName(Class clazz) {
        Field[] declaredFields = clazz.getDeclaredFields();
        String[] fieldNames = new String[declaredFields.length];
        for (int i = 0; i < declaredFields.length; i++) {
            fieldNames[i] = declaredFields[i].getName(); //通过反射获取属性名
        }
        return fieldNames;
    }
}
